/**
 * @description 图表组件
 * @author 大肘子
 */

import React, { FC, useEffect, useState } from "react";
import { useParams } from "react-router-dom";
import { getChartData } from "../../../service";
import { useRequest } from "ahooks";
import { Spin } from "antd";
//根据type获取组件
import { getComponentConfigByType } from "../../../questionComponents";
import { QuestionCheckboxStatType } from "../../../questionComponents/questionCheckbox/tepy";

type propsType = {
  selectedId: string;
  selectedType: string;
};

const ChartStat: FC<propsType> = (props) => {
  const { selectedId, selectedType } = props;
  const { id = "" } = useParams();
  const [statList, setstatList] = useState<QuestionCheckboxStatType[]>([]);
  const { loading, run } = useRequest(
    async () => {
      const res = await getChartData(id, selectedId);
      return res;
    },
    {
      manual: true,
      onSuccess(res) {
        setstatList(res.stat);
      },
    },
  );
  function getStatComponent(type: string, list: Array<any>) {
    const componentConfig = getComponentConfigByType(type);
    if (componentConfig == null) return null;
    const { StatComponent } = componentConfig;
    if (StatComponent == null) return <div style={{ textAlign: "center", margin: "20px 0" }}>该组件没有统计数据</div>;
    return <StatComponent list={statList}></StatComponent>;
  }
  useEffect(() => {
    run();
  }, [selectedId, id]);
  if (loading)
    return (
      <div style={{ textAlign: "center", margin: "20px 0" }}>
        <Spin></Spin>
      </div>
    );
  return getStatComponent(selectedType, statList);
};

export default ChartStat;
